/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package serwer;

import Serializable.ParsedCmd;

/**
 *
 * @author Marcin
 */
public class Parser {
    
    public static ParsedCmd parse(String in){
        ParsedCmd pC = new ParsedCmd();
        char type=in.charAt(0);
        String rest=in.substring(1);
        if(hasEnd(in))
            pC.end=true;
        else
            pC.end=false;
        switch(type){
            case '-': //basic command
                if(!pC.end)
                    pC.mainCmd = rest;
                else
                    pC.mainCmd = rest.substring(0, rest.length()-2);
                break;
            case '@': //command + single int
                pC.mainCmd=parseCmd(rest);
                pC.intParam=new int[1];
                pC.intParam[0]=parseInt(rest);
                break;
            case '$': //command + string parametr
                pC.mainCmd=parseCmd(rest);
                pC.stringParam = new String[1];
                pC.stringParam[0]=parseStringParam(rest);
                break;
        }
        
        return pC;
    }
    
    public static String parseCmd(String in){
        int dashPos=in.indexOf("^");
        if(dashPos==-1) return in;
        return in.substring(0, dashPos);
    }
    
    public static boolean hasEnd(String str){
        return str.substring(str.length()-2).equals("##");
    }
    
    public static String parseStringParam(String in){
        int dashPos = in.indexOf("^");
        if(dashPos==-1) return "";
        if(hasEnd(in))
            return in.substring(dashPos+1, in.length()-2);
        else
            return in.substring(dashPos+1, in.length());
    } 
    
    public static int parseInt(String in){
        int dashPos = in.indexOf("^");
        if(dashPos==-1) return 0;
        String out;
        if(hasEnd(in))
            out = in.substring(dashPos+1, in.length()-2);
        else
            out = in.substring(dashPos+1, in.length());
        return Integer.parseInt(out);
    } 
}
